package com.sky.controller.admin;


import com.sky.properties.AliOssProperties;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "通用接口,文件上传")
public class CommonController {

//    @Autowired
//    private AliOssProperties aliOssProperties;


    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public Result<String> upload(@RequestPart MultipartFile file){
        log.info("文件上传：{}",file);

        /**
         * 1.获取文件的原始文件名 100.jsp
         * 2.修改原始文件名    获取文件的后缀名
         * 3.UUID生成字符串当作文件名
         * 4.调用AliOssUtils 上传文件
         * 5.返回上传文件的访问路径
         */
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String suffix = originalFilename.substring(index);
        String newFileName = UUID.randomUUID().toString()+suffix;

        //AliOssUtil
//        AliOssUtil aliOssUtil = new AliOssUtil(aliOssProperties.getEndpoint(),aliOssProperties.getAccessKeyId(),aliOssProperties.getAccessKeySecret(),aliOssProperties.getBucketName());
        try {
            String fileUrl = aliOssUtil.upload(file.getBytes(), newFileName);
            return Result.success(fileUrl);
        } catch (IOException e) {
            return Result.error("文件上传失败");
        }

    }
}